//
//  JSPhotoPickerAssetsCollectionViewCell.m
//  JSPhotoPicker
//
//  Created by JasonLee on 2018/8/13.
//  Copyright © 2018年 JasonLee. All rights reserved.
//

#import "JSPhotoPickerAssetsCollectionViewCell.h"
#import "JSPhotoPickerDatas.h"
#import "JSPhotoPickerCommon.h"
@interface JSPhotoPickerAssetsCollectionViewCell()

@end
@implementation JSPhotoPickerAssetsCollectionViewCell
-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self createView];
    }
    return self;
}
-(void)createView{
    self.imageView = [[UIImageView alloc] init];
    self.imageView.frame = self.contentView.bounds;
    self.imageView.backgroundColor = UIColor.redColor;
    self.imageView.contentMode = UIViewContentModeScaleAspectFill;
    self.imageView.clipsToBounds = YES;
    self.imageView.userInteractionEnabled = YES;
    [self.contentView addSubview:self.imageView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    [self.imageView addGestureRecognizer:tap];
    
    self.selectButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.selectButton.frame = CGRectMake(self.contentView.bounds.size.width - 28, 3, 25, 25);
    [self.selectButton setImage:[UIImage imageNamed:JSPhotoPickerSrcName(@"icon_image_no")] forState:UIControlStateNormal];
    [self.selectButton setImage:[UIImage imageNamed:JSPhotoPickerSrcName(@"icon_image_yes")] forState:UIControlStateSelected];
    [self.selectButton addTarget:self action:@selector(selectTapAction) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:self.selectButton];

}
-(void)tapAction{
    if ([self.delegate respondsToSelector:@selector(js_photoPickerCollectionImageViewTapAction:andPHAsset:)]) {
        [self.delegate js_photoPickerCollectionImageViewTapAction:self.imageView andPHAsset:self.asset];
    }
}
-(void)selectTapAction{
    if ([self.delegate respondsToSelector:@selector(js_photoPickerCollectionSelectedAction: andPHAsset:)]) {
        [self.delegate js_photoPickerCollectionSelectedAction:self.selectButton andPHAsset:self.asset];
    }
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
    animation.duration = 0.25;
    animation.autoreverses = YES;
    animation.values = @[@1,@1.2,@1];
    animation.fillMode = kCAFillModeForwards;
    [self.selectButton.layer addAnimation:animation forKey:nil];
}
-(void)updateCellWithPHAsset:(PHAsset *)asset andSelected:(BOOL)selected{
    self.selectButton.selected = selected;
    if (self.asset != asset) {
        self.asset = asset;
        typeof (self)weakSelf = self;
        [[JSPhotoPickerDatas defaultPicker] getAssetsImageWithAsset:asset targetSize:CGSizeMake(90, 90) sys:NO andFinish:^(id objc) {
            weakSelf.imageView.image = objc;
        }];
    }
}
@end
